﻿using System;
using System.Collections.Generic;
using System.Data;
using CLFramework.Utility;
using CLFramework.WinService;
using HQDBF;

namespace CarolLib.Task
{
    /// <summary>
    /// 按分钟从行情库获取ETF股票价格数据并保存
    /// </summary>
    public class DBFRealtimePrice : IBasicTask
    {
        #region IBasicTask Members

        public void Exit()
        {
        }

        public void Init()
        {
        }

        public void Execute()
        {
            if (DateTime.Today.DayOfWeek == DayOfWeek.Saturday || DateTime.Today.DayOfWeek == DayOfWeek.Sunday)
            {
                Log.Info("今天周末，非交易日");
                return;
            }


            if (DateTime.Now.Hour < 9 || DateTime.Now.Hour > 23)
            {
                Log.Info("非交易时间");
                return;
            }

            //1. 获取实时数据
            PriceQuery query = new PriceQuery();

            var tb = query.OpenQueryTable(CHK, false);
            if (tb.Rows.Count > 0 && tb.Rows[0][0].ToString() != DateTime.Today.ToString("yyyyMMdd"))
            {
                Log.Info("当前行情是交易日(" + tb.Rows[0][0].ToString() + ")，" + "不是今天（" + DateTime.Today.ToString("yyyyMMdd") + "）,暂不执行");
                return;
            }

            //todo:检查是否交易日
            //note:策略：获得最近一次的价格，。。。呃，还是不行

            Log.Info("开始保存...");

            DateTime start = DateTime.Now;

            try
            {

                var table = query.OpenQueryTable(GET_SH_PRICE, true);
                var table2 = query.OpenQueryTable(GET_SZ_PRICE, false);

                table.Merge(table2);

                Log.Info("获取价格完成，耗毫秒数：" + (DateTime.Now - start).TotalMilliseconds.ToString());

                //2. 创建价格实体列表
                List<ETFPrice> list = new List<ETFPrice>();
                foreach (DataRow row in table.Rows)
                {
                    var etf = new ETFPrice(row["Code"].ToString(), Convert.ToDouble(row["Price"].ToString()));

                    //debug
                    //etf.Price += (etf.Price * (new Random().NextDouble() - 0.5));

                    list.Add(etf);
                }

                new ETFPriceQuery().SavePrice(list);
            }
            catch (Exception e)
            {
                Log.Exception("保存ETF价格失败：" + e.Message, e);
            }
            Log.Info("保存完成，共耗毫秒数：" + (DateTime.Now - start).TotalMilliseconds.ToString());
        }

        #endregion

        static readonly string CHK = "SELECT HQZQJC AS LastDate FROM SJSHQ WHERE HQZQDM='000000'";
        readonly string GET_SH_PRICE = "SELECT S1 AS Code, S8 AS Price FROM Show2003 WHERE S2 LIKE '%ETF%'";
        readonly string GET_SZ_PRICE = "SELECT HQZQDM AS Code, HQZJCJ AS Price FROM SJSHQ WHERE HQZQJC LIKE '%ETF%'";
    }
}
